package com.taskschecker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.taskschecker.db.DBManager;
import com.taskschecker.db.TaskGroup;

public class TaskGroupListActivity extends Activity {

	private DBManager mgr;
	private ListView taskGroupListView;
	private List<String> groupIds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_group_list);

		taskGroupListView = (ListView) findViewById(R.id.taskGroupListView);

		Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
		buttonAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg) {
				Intent intent = new Intent(TaskGroupListActivity.this,
						TaskGroupAddActivity.class);
				startActivity(intent);
			}
		});

		updateList();
	}

	private void updateList() {
		mgr = new DBManager(this);
		List<TaskGroup> taskgroups = mgr.taskGroupList();
		List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		groupIds = new ArrayList<String>();
		for (TaskGroup taskgroup : taskgroups) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", android.R.drawable.ic_dialog_info);
			map.put("content", taskgroup.getContent());
			groupIds.add(Integer.toString(taskgroup.getTaskgroupid()));
			listItem.add(map);
		}
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,
				R.layout.task_group_list_item, new String[] { "ItemImage",
						"content" },
				new int[] { R.id.ItemImage, R.id.ItemTitle });
		taskGroupListView.setAdapter(listItemAdapter);
		taskGroupListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(TaskGroupListActivity.this,
						TaskGroupInfoActivity.class);
				intent.putExtra("groupId", groupIds.get(arg2));
				startActivity(intent);

			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		updateList();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mgr.closeDB();
	}
}
